<?php 
header('content-type:text/html;charset=utf-8');
//2.接收信息

$act=$_GET['act'];
if($act!=='select'){
	$data=json_decode($_POST['mydata'],true);
}
if($act==='add'){
	add($data);
}elseif($act==='dele'){
	dele($data);
}elseif($act==='update'){
	update($data);
}elseif($act==='select'){
	select();
}elseif($act==='selectByWeek'){
	selectByWeek();
}elseif($act==='selectByfy'){
	selectByfy($data);
}

function database($str){
	$servername = "localhost";
	$username = "cb";
	$password = "root";
	$dbname = "demo";
	// 创建连接
	$conn = new mysqli($servername, $username, $password, $dbname);
	// Check connection
	if ($conn->connect_error) {
	    die("连接失败: " . $conn->connect_error);
	} 
	 
	$sql = $str;
	$result = $conn->query($sql);
	$conn->close();
	return $result;
}

function add($user)
{
	$sql="INSERT INTO myday (time, grade, rank) 
	VALUES ('".$user["time"]."', '".$user["grade"]."', '".$user["rank"]."')";
	$ret = database($sql);
	if($ret){
		echo 'success';
	}
}

function dele($user)
{
	$sql="DELETE FROM myday WHERE id='".$user["id"]."'";
	$ret = database($sql);
	if($ret){
		echo 'success';
	}
}

function update($user)
{
	$sql="UPDATE myday SET time = '".$user["time"]."', grade = '".$user["grade"]."', rank='".$user["rank"]."' WHERE id = '".$user["id"]."'";
	$ret = database($sql);
	if($ret){
		echo 'success';
	}
}

function select()
{
	$sql = "SELECT * FROM myday";
	$ret = database($sql);
	$array= array();
	while($row = $ret->fetch_assoc()) {
		array_push($array,$row);
	}
	echo json_encode($array);
}

function selectByWeek()
{
	$startime = date('Y-m-d', (time() - ((date('w') == 0 ? 7 : date('w')) - 1) * 24 * 3600));
	$endtime = date('Y-m-d', (time() + (7 - (date('w') == 0 ? 7 : date('w'))) * 24 * 3600));
	$sql = "SELECT * FROM myday WHERE time BETWEEN '".$startime."' AND '".$endtime."'";
	$ret = database($sql);
	$array= array();
	while($row = $ret->fetch_assoc()) {
		array_push($array,$row);
	}
	echo json_encode($array);
	
}

function selectByfy($obj)
{
	$sql = "SELECT * FROM myday LIMIT ".$obj["star"].",".$obj["len"];
	$ret = database($sql);
	$array= array();
	while($row = $ret->fetch_assoc()) {
		array_push($array,$row);
	}
	echo json_encode($array);
}